﻿using UnityEngine;
using System.Collections;

public class Weapon : MonoBehaviour {

	public float Damage = 0;
	public Transform Owner = null;
	///The lifetime of the attack, in seconds.
	///Set to 0 to indicate infinite length attack. 
	public float Lifetime = 0;
	public float Size = 1;
	/// <summary>
	/// If true, removes the weapon from the game world on impact.
	/// </summary>
	public bool RemoveOnImpact = true;
    public Vector3 AttackDirection = Vector3.zero;
    public float WeaponVelocity = 0.0f;
    public float KnockbackForce = 120.0f;

	private float instLifetime;

	// Use this for initialization
	void Start () {
		instLifetime = Lifetime;
	}
	
	// Update is called once per frame
	void Update () {
		instLifetime -= Time.deltaTime;
		if(instLifetime <= 0)
		{
			GameObject.Destroy(gameObject);
		}
        transform.Translate(-AttackDirection * WeaponVelocity * Time.deltaTime);
	}

	void OnTriggerEnter(Collider other)
	{
		//TODO: spawn dust flare & explosion
		//inflict damage if possible
		HealthInfo hitHealth = other.transform.GetComponent<HealthInfo>();
        if (hitHealth != null && hitHealth.transform != Owner)
        {
            hitHealth.ApplyDamage(Damage);
            //also knock the entity back if possible!
            Rigidbody targetRb = hitHealth.rigidbody;
            if (targetRb != null)
            {
                targetRb.AddForce(AttackDirection * KnockbackForce);
            }
        }
        else
        {
            Debug.Log("No health info; can't damage");
        }
		if(RemoveOnImpact)
		{
			GameObject.Destroy(gameObject);
		}
	}
}
